package com.study.zgw.byteBuffer;

import com.study.zgw.messageDemo.GroupJoinRequestMessage;
import com.study.zgw.messageDemo.LoginRequestMessage;
import com.study.zgw.messageDemo.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestMessageCodec {
    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(LogLevel.DEBUG),
                new LengthFieldBasedFrameDecoder(1024,12,4,0,0),
                new MessageCodec()
        );

        //encode
        LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123", "张三");
        channel.writeOutbound(message);

        //decode
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null, message, byteBuf);

        ByteBuf s1 = byteBuf.slice(0, 100);  //slice 零拷贝 s1与s2的内存地址都是byteBuf的地址
        ByteBuf s2 = byteBuf.slice(100, byteBuf.readableBytes() - 100);

        s1.retain();
        channel.writeInbound(s1);  //这里写完后会调用byteBuf release方法
        channel.writeInbound(s2);
    }
}
